<?php

namespace app\service;

use app\common\BaseService;
use app\model\User as UserModel;
use think\facade\Db;

class UserService extends BaseService
{
  public static function getInstance(): UserService
  {
    return parent::getInstance();
  }

  public static function getModel(): UserModel
  {
    return UserModel::getInstance();
  }

  /*
   * 通过condition获取User
   */
  public function getUserByCondition($conditions = [], $order = ['id' => 'desc']) {
    $query = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    $result = $query->select()->toArray();
    return $result;
  }

  /*
   * 通过condition获取User关联role
   */
  public function getUserJoinRoleCondition($conditions, $order = ['u.id' => 'desc']) {
    $conditions[] = ['u.status', 1, '='];
    $conditions[] = ['r.status', 1, '='];
    $query = Db::name('user')
      ->alias('u')
      ->field('u.*, r.rolename, r.contents_ids')
      ->join('role r', 'r.id = u.role_id', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    return $query->select()->toArray();
  }

  /*
   * 通过condition获取User关联task
   */
  public function getUserJoinTaskCondition($conditions = [], $order = ['u.id' => 'desc']) {
    $conditions[] = ['u.status', 1, '='];
    $query = Db::name('user')
      ->alias('u')
      ->field('u.id,u.truename,t.id as task_id,t.dev_status,t.check_status,t.is_check,t.task_user_id,t.status,p.status as project_status')
      ->join('task t', 't.task_user_id = u.id', 'LEFT')
      ->join('project p', 't.project_id = p.id', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    return $query->select()->toArray();
  }

  public static function updateUser($id, $update) {
    return self::getModel()
      ->where('id', $id)
      ->update($update);
  }

}